$(function () {
    let timer;
    //文本框工具类
    let inputUtil = new Input_util();
    let addAddress = $(".add-address");
    //地址工具类
    let addressUtil = new Address_util();
    let addressValue = addressUtil.addressValue();


    $(".more").on({
        mouseenter: function () {
            $(".more").css({"display": "block"})
        },
        mouseleave: function () {
            $(".more").css({"display": "none"})
        }
    });

    $(".drop-down").on({
        mouseenter: function () {
            // 取消之前设置的延迟执行
            clearTimeout(timer);
            let boxId = $(this);
            // 设置延迟执行操作
            timer = setTimeout(function () {
                // 在延迟时间后执行操作
                if ($(boxId[0]).attr("class") !== "more drop-down") {
                    $(".more").css({"display": "none"})
                }
            }, 2000);
            // 设置延迟时间（单位为毫秒）
        },
        mouseleave: function () {
            // 取消之前设置的延迟执行
            clearTimeout(timer);

            let boxId = $(this);
            if ($(boxId[0]).attr("class") !== "more drop-down" &&
                $(boxId[0]).attr("class") !== "username options drop-down") {
                $(".more").css({"display": "none"})
            }
        }
    });

    $(".drop-down-menu").on({
        mouseenter: function () {
            $(".options-img").attr({"src": "http://localhost:8083/resource_packs/images/drop_down_color.png"})
            $(".more").css({"display": "block"})
        }, mouseleave: function () {
            $(".options-img").attr({"src": "http://localhost:8083/resource_packs/images/drop_down.png"})
        }
    });

    addAddress.on({
        mouseenter: function () {
            $(".add-address-img img").attr({"src": "http://localhost:8083/resource_packs/images/add_color.png"})
            $(".add-address-word").css({"color": "#b0b0b0"})
        }, mouseleave: function () {
            $(".add-address-img img").attr({"src": "http://localhost:8083/resource_packs/images/add_address.png"})
            $(".add-address-word").css({"color": "#E0E0E0"})
        }
    });
    let removeImg = $(".remove-img");
    removeImg.on({
        mouseenter: function () {
            removeImg.attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes_red.png"})
        }, mouseleave: function () {
            removeImg.attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes.png"})
        }
    });
    let hintImg = $(".hint-img");
    hintImg.on({
        mouseenter: function () {
            hintImg.attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes_red.png"})
        }, mouseleave: function () {
            hintImg.attr({"src": "http://localhost:8083/resource_packs/images/pop_ups_closes.png"})
        }
    });

    let revise = $(".revise-name");
    //动画
    inputUtil.customizeAfloatAnimation($($(".name")[0]), $(".name-title"), revise[0], 0, -20)
    //动画
    inputUtil.customizeAfloatAnimation($($(".phone-number")[0]), $(".phone-title"), revise[1], 0, -20)
    //动画
    let address = $(".specific-address");

    inputUtil.customizeAfloatAnimation($(address[0]), $(".address-character"), address, 0, -20)
    inputUtil.customizeAfloatAnimation($($(".address-label")[0]), $(".label-word"), $(".label"), 0, -20)
    hintImg.on("click", function () {
        $(".hint").css("display", "none")
    })
    addAddress.on("click", function () {
        $($(".address-word")[0]).text("省级 市级 区县 区域")
        $($(".specific-address")[0]).val("")
        $($(".hint")[0]).css("display", "block")
    })
    $(".cancel").on("click", function () {
        $(".hint").css("display", "none")
    })
    $(".confirm").on("click", function () {
        $(".hint").css("display", "none")
    })

    let editAddress = $(".edit-address")
    let selectedRegions = $(".region-selection")
    let selectAddress = $(".select-address");

    editAddress.on("click", function () {
        //地址
        let address = "";
        for (const address of addressValue) {
            //显示省份
            selectAddress.append("<a class='choose-province'>" + address.name + "</a>")
        }
        let province = $(".choose-province")
        //显示市
        province.on("click", function () {
            let thisProvince = $(this).text();

            address += thisProvince;
            $(".address-word").text(address)

            // 使用数组的 find() 方法查询数据
            let result = addressValue.find(function (item) {
                $(".province span").text("选择城市/地区")
                return item.name === thisProvince;
            });
            //显示城市
            selectAddress.empty();
            for (const resultIndex in result.city) {
                selectAddress.append("<a class='city'>" + result.city[resultIndex].name + "</a>")
            }

            //显示区
            $(".city").on("click", function () {
                $(".province span").text("选择区县")
                let thisDistrict = $(this).text();
                address += " " + thisDistrict;
                $(".address-word").text(address)
                let city = null;
                addressValue.find(function (item) {
                    for (const cityIndex in item.city) {
                        if (item.city[cityIndex].name === thisDistrict) {
                            city = item.city[cityIndex]
                            break;
                        }
                    }
                });
                selectAddress.empty();
                for (const districtIndex in city.area) {
                    selectAddress.append("<a class='district'>" + city.area[districtIndex] + "</a>")
                }
                $(".district").on("click", function () {
                    address += " " + $(this).text();
                    console.log(address)
                    $(".address-word").text(address)
                    selectAddress.empty();
                    selectedRegions.css("display", "none")
                })
            })
        })
        selectedRegions.css("display", "block")
    })
    removeImg.on("click", function () {
        selectAddress.empty();
        selectedRegions.css("display", "none")
    })
    $(".use-coupon").on("click", function () {
        $($(".hint")[1]).css("display", "block")
    })
    let orderSettlement = new Order_settlement();
    $(".btn-primary").on("click", function () {
        let couponStr = $($(".coupon label input:checked")[0]).val();
        //转JSON
        let objectToJson = new Text_util().objectToJson(couponStr);
        console.log(objectToJson);
        let preferential = $(".preferential")
        $(".use_coupon").remove();

        preferential.append("<div class='use_coupon'>" +
            "<img src='http://localhost:8083/resource_packs/images/use_coupon.png' alt='使用优惠卷'>" +
            "<span>正在使用：" + objectToJson.couponTitle + "</span>" +
            "<a class='use-coupon'>修改&emsp;></a>" +
            "</div>")
        $(".use-coupon").on("click", function () {
            $($(".hint")[1]).css("display", "block")
        })
        $(".confirm-order").attr("coupon-id", objectToJson.couponId)
        $($(".hint")[1]).css("display", "none")
        $(".coupons").remove();

        //计算总额 和 折扣
        orderSettlement.OrderDiscount($(this).attr("total"), objectToJson.discount).then(res => {
            console.log(res.trim().split(","))
            let valueArr = res.trim().split(",");
            $(".coupon-credit-amount").text("-" + valueArr[1] + "元");
            $(".total a").text(valueArr[0])
        })
    })
    $(".revise").on("click", function () {
        let addressStr = $(this).attr("address");
        //转JSON
        let objectToJson = new Text_util().objectToJson(addressStr);
        console.log(objectToJson)
        $(".update-address-confirm").attr("address-id", objectToJson.addressId)
        $(".update-name").val(objectToJson.addressName)
        $(".update-phone-number").val(objectToJson.addressPhone)
        $(".update-address-word").text(objectToJson.addressProvince + " "
            + objectToJson.addressCity + " "
            + objectToJson.addressDistrict)
        $(".update-specific-address").val(objectToJson.fullAddress)
        $(".update-address-lable").val(objectToJson.addressLabels)
        $($(".hint")[2]).css("display", "block")
        let revise = $(".revise-name");
        //动画
        let address = $(".specific-address");
        inputUtil.customAnimationAids($(".update-name"), $(".name-title")[1], revise[2], 0, -20)
        inputUtil.customAnimationAids($(".update-phone-number"), $(".phone-title")[1], revise[3], 0, -20)
        inputUtil.customAnimationAids($(".update-specific-address"), $(".address-character")[1], address[1], 0, -20)
        inputUtil.customAnimationAids($(".update-address-lable"), $(".label-word")[1], $(".label")[1], 0, -20)

        //动画
        inputUtil.customizeAfloatAnimation($($(".name")[1]), $(".name-title"), revise[2], 0, -20)
        //动画
        inputUtil.customizeAfloatAnimation($($(".phone-number")[1]), $(".phone-title"), revise[3], 0, -20)

        inputUtil.customizeAfloatAnimation($(address[1]), $(".address-character"), address[1], 0, -20)
        inputUtil.customizeAfloatAnimation($($(".address-label")[1]), $(".label-word"), $(".label")[1], 0, -20)
    })
    let gaud = new Gaud();
    $(".update-address-confirm").on("click", function () {
        let address = $(".update-address-word").text().split(" ");
        gaud.getCurrentLatitudeAndLongitude($(".update-address-word").text() + $(".update-specific-address").val()).then(res => {
            let addressJson = {
                addressId: $(this).attr("address-id"),
                addressName: $(".update-name").val(),
                addressPhone: $(".update-phone-number").val(),
                addressProvince: address[0],
                addressCity: address[1],
                addressDistrict: address[2],
                fullAddress: $(".update-specific-address").val(),
                addressLabels: $(".update-address-lable").val(),
                longitude: res.lng,
                latitude: res.lat
            }
            orderSettlement.saveOrUpdateAddress(JSON.stringify(addressJson)).then(res => {
                console.log(res)
                location.reload();
            })
        })
    })
    $(".positioning").on("click", function () {
        gaud.getCity().then(res => {
            $(".address-word").text(res.province + " " + res.city + " " + res.district)
            $(".region-selection").css("display", "none")
            $(".select-address").empty()

        });
        gaud.getCurrentLocation().then(res => {
            console.log(res)
            $(".specific-address").val(res)
            inputUtil.customAnimationAids($(".specific-address"), $(".address-character"), $(".specific-address"), 0, -20)
        })

    })
    $($(".confirm")[0]).on("click", function () {
        let address = $(".address-word").text().split(" ");
        gaud.getCurrentLatitudeAndLongitude($(".address-word").text() + $($(".specific-address")[0]).val()).then(res => {
            let addAddressJson = {
                addressName: $($(".name")[0]).val(),
                addressPhone: $($(".phone-number")[0]).val(),
                addressProvince: address[0],
                addressCity: address[1],
                addressDistrict: address[4],
                fullAddress: $($(".specific-address")[0]).val(),
                addressLabels: $($(".address-label")[0]).val(),
                informationId: $(this).attr("information-id"),
                longitude: res.lng,
                latitude: res.lat
            }
            orderSettlement.saveOrUpdateAddress(JSON.stringify(addAddressJson)).then(res => {
                location.reload();
            }).catch(reason => {
                console.log(reason)
            })
        });
    })
    $(".shipping-address-selection").on("click", function () {
        $(".shipping-address-selection").css("border", "1px solid #e0e0e0")
        $(this).css("border", "1px solid #FF6A00")
        let parentElement = this;
        let targetElement = event.target;

        // 判断目标元素是否是父元素本身
        if (parentElement === targetElement) {
            // 执行父元素点击事件的操作
            orderSettlement.updateIsSelectedAddress(null, 1).then(res => {
                orderSettlement.updateIsSelectedAddress($(this).attr("address-id"), 0).then(res => {
                    location.reload();
                })
            })
        }
    })
    $(".confirm-order").on("click", function () {
        let texts = [];
        $(".quantity").each(function() {
            texts.push($(this).text());
        });
        let quantity = texts.join(",");
        let orders = new Orders();
        let couponCredit = $(".coupon-credit-amount").text().split('元')[0].split('-')[1];
        orders.addOrders($(this).attr("longitude"), $(this).attr("latitude"),
            $(this).attr("total-quantity"), $(this).attr("total-price"),
            $(this).attr("freight"), $(this).attr("information-id"),
            couponCredit, $(this).attr("coupon-id"),quantity).then(res => {
            //工具包
            let textUtil = new Text_util();

            //清空空格
            let orderNumber = textUtil.clearSpaces(res);
            if (orderNumber === "false"){
                alert("请选中地址")
            }else{
                //加密
                let aesKeyUtil = new Aes_key_util();
                const encryptedInformationId = aesKeyUtil.encrypt($(this).attr("information-id"));

                //跳转支付页面
                window.location.replace("http://localhost:8083/www.xiaomi.com/pay?informationId=" +
                    encodeURIComponent(encryptedInformationId) + "&accountId=" + $(this).attr("account-id") + "&orderId=" + orderNumber);
            }
        }).catch(reason => {
            console.log(reason)
        })
    })

})